package com.bwie.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.bwie.exception.BusinessException;
import com.bwie.mapper.*;
import com.bwie.mq.OrderParkProducer;
import com.bwie.pojo.dto.OrderParkDto;
import com.bwie.pojo.po.*;
import com.bwie.pojo.vo.UserVo;
import com.bwie.service.OrderParkService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderParkServiceImpl implements OrderParkService {
    @Autowired
    private OrderParkMapper orderParkMapper;
    @Autowired
    private ParkMapper parkMapper;

    @Autowired
    private HttpSession session;
    @Autowired
    private ChargingMapper chargingMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BillMapper billMapper;
    @Autowired
    private MonthCarMapper monthCarMapper;

    @Autowired
    private OrderParkProducer orderParkProducer;
    @Override
    public PageInfo<OrderPark> getOrderPark(OrderParkDto orderParkDto) {
        PageHelper.startPage(orderParkDto.getPageNum(),orderParkDto.getPageSize());

        User user = (User) session.getAttribute("user");
       List<OrderPark> list =  orderParkMapper.getOrderPark(user.getUserId());
        PageInfo<OrderPark> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Transactional
    @Override
    public void addOrderPark(OrderParkDto orderPark) throws ParseException {
        UserVo userVo = (UserVo) session.getAttribute("user");
        OrderPark orderPark2 = new OrderPark();
        BeanUtils.copyProperties(orderPark,orderPark2);


        Integer parkId = orderPark.getParkId();
        String carCard = orderPark.getCarCard();
        Integer carType = orderPark.getCarType();
        String startTime1 = orderPark.getStartTime();
        String endTime1 = orderPark.getEndTime();
        if (parkId==null||
                StringUtils.isEmpty(carCard)||
                carType==null||
                startTime1==null||
                endTime1==null){
            throw new BusinessException("数据不完整，请重新输入");
        }

        //查询车位剩余数量
        Park park = parkMapper.selectNumByParkId(orderPark.getParkId());
        Integer parkNumber = park.getParkNumber();
        if (parkNumber<=0){
            throw new BusinessException("暂无车位");
        }

        OrderPark orderPark1 = orderParkMapper.selectOrderByCarCard(orderPark.getCarCard());
        if (orderPark1!=null){
            throw new BusinessException("该车牌已预订，不能再次预订");
        }




        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = sdf.parse(startTime1);
        Date endTime = sdf.parse(endTime1);
        //相隔时间（小时）
        long minutes = DateUtil.between(startTime, endTime, DateUnit.MINUTE);
        long hours=minutes/60;
        long ys = minutes%60;
        if (ys>30){
            hours=hours+1;
        }
        //计算金额
        Charging charging = chargingMapper.selectChargingById(orderPark.getParkId(),orderPark.getCarType());

        BigDecimal chargingPrice = charging.getChargingPrice();
        BigDecimal bidHours = new BigDecimal(hours);
        BigDecimal sumMoney=chargingPrice.multiply(bidHours);
        orderPark2.setSumMoney(sumMoney);



        orderPark2.setStartTime(startTime);
        orderPark2.setEndTime(endTime);
        //添加订单
        orderPark2.setUserId(userVo.getUserId());
        orderParkMapper.doAdd(orderPark2);


        //车位减一
        parkMapper.updNum(orderPark.getParkId());

    }

    @Transactional
    @Override
    public void updOrderParkType(OrderPark orderPark) {
        //支付状态判断
        if (orderPark.getRechargeState()==1){
            throw new BusinessException("已支付过该订单，不能重复支付！！！");
        }
        BigDecimal sumMoney = orderPark.getSumMoney();
        Integer userId = orderPark.getUserId();



        //判断支付方式
        Integer rechargeType = orderPark.getRechargeType();
        //余额支付
        if (rechargeType==0){
            //账户余额查询
            User user = userMapper.getUserById(userId);
            BigDecimal userMoney = user.getUserMoney();
            int i = userMoney.compareTo(sumMoney);
            if (i<0){
                throw new BusinessException("余额不足，请充值");
            }
            //修改余额
            userMapper.updMoney(userId,sumMoney);
        }

        if (rechargeType==1){
            Integer parkId = orderPark.getParkId();
            String carCard = orderPark.getCarCard();
            Date date = new Date();
            //查看是否有可用月卡
            MonthCar monthCar = monthCarMapper.selectMonthCar(parkId,carCard,date);

            if (null==monthCar){
                throw new BusinessException("无可用月卡，请办理或更换支付方式");
            }
            orderPark.setSumMoney(new BigDecimal(0));
        }



        //修改支付状态
        orderParkMapper.updOrderPark(orderPark);
        //扣减用户余额成功后，并将本次消费记录保存到交易流水记录表中
        Bill bill = new Bill();
        bill.setBillMoney(orderPark.getSumMoney());
        bill.setUserId(userId);
        bill.setBillTime(new Date());
        bill.setBillType(orderPark.getRechargeType());
        bill.setParkId(orderPark.getParkId());
        bill.setOrderParkId(orderPark.getOrderParkId());
        billMapper.addBill(bill);

        User userById = userMapper.getUserById(userId);
        orderParkProducer.SmsOrderPark(userById);




    }

    @Override
    @Transactional
    public void cleanOrderPark(OrderPark orderPark) {
        Integer rechargeState = orderPark.getRechargeState();
        if (rechargeState!=0){
            throw new BusinessException("已支付订单无法取消！！！");
        }
        //修改状态为已取消
        orderParkMapper.updOrderParkState(orderPark.getOrderParkId(),2);


        //车位加1
        parkMapper.updNum1(orderPark.getParkId());
    }

    @Override
    public OrderPark getOrderParkById(Integer orderParkId) {

        OrderPark orderPark = orderParkMapper.getOrderParkById(orderParkId);

        return orderPark;
    }


}
